package com.itheima.task;

import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Set;

@Slf4j
@Component
public class Mytask {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AliOssUtil aliOssUtil;

    @Scheduled(cron = "0 0 1 * * ?")
    //@Scheduled(cron = "0/60 * * * * ?")
    public void cleanGarbageImages() {
        // 1. 计算两个集合的差值：uploaded_images - valid_images
        Set<String> garbageImages = redisTemplate.opsForSet().difference("uploaded_images", "valid_images");

        if (!garbageImages.isEmpty()) {
            // 2. 删除 OSS 中的垃圾图片
            deleteFromOSS(garbageImages);
            // 3. 从 Redis 中移除已处理的图片
            redisTemplate.opsForSet().remove("uploaded_images", garbageImages.toArray(new String[0]));
            System.out.println("清理完成，共删除 " + garbageImages.size() + " 张垃圾图片");
        }
    }
    private void deleteFromOSS(Set<String> imageNames) {
        for (String imageName : imageNames) {
            try {
                aliOssUtil.delete(imageName); // 删除 OSS 文件
                System.out.println("删除 OSS 图片：" + imageName);
            } catch (Exception e) {
                System.err.println("删除 OSS 图片失败：" + imageName + ", 原因：" + e.getMessage());
            }
        }
    }
    // @Scheduled(cron = "0/5 * * * * ?")
    public void executeTask(){
        log.info("定时任务开始执行:{}",new Date());
    }

}
